from artifacts.base.sr.relics_impl import *
from artifacts.base.base_artifacts import Artifacts
from artifacts.base.sr.relics_factory import RelicsFactory
from artifacts.evaluate.sr.billet_evaluate import evaluate

score_need = 1


def out_complete(equip_map):
    return equip_map.get(Head) is not None \
           and equip_map.get(Hands) is not None \
           and equip_map.get(Body) is not None \
           and equip_map.get(Feet) is not None


def in_complete(equip_map):
    return equip_map.get(Link) is not None \
           and equip_map.get(Sphere) is not None


def update_cur_equip(equip_map, relics):
    relics.upgrade_max()
    score = evaluate(relics)
    if score >= score_need:
        cur_equip = equip_map.get(type(relics))
        if cur_equip is None or cur_equip['score'] < score:
            equip_map[type(relics)] = {'relics': relics, 'score': score}
            return True
    return False


def get_need_out_relics_type(equip_map, type_priority):
    for item in type_priority:
        if equip_map.get(item) is None:
            return item
    return type_priority[0]


def once_need_times(display=True):
    times = 0
    equip_map = {}
    salvage_count = 0
    while not out_complete(equip_map):
        times += 1
        out_relics_list = RelicsFactory.create_out_relics_list()
        for relics in out_relics_list:
            equip_updated = False
            if relics.suit is Artifacts.SUIT_A:
                equip_updated = update_cur_equip(equip_map, relics)
            if not equip_updated:
                salvage_count += 1
        if salvage_count >= 10:
            salvage_count -= 10
            synthetic_relics = get_need_out_relics_type(equip_map, [Body, Feet, Hands, Head])(Artifacts.SUIT_A)
            equip_updated = update_cur_equip(equip_map, synthetic_relics)
            if not equip_updated:
                salvage_count += 1

    while not in_complete(equip_map):
        times += 1
        in_relics_list = RelicsFactory.create_in_relics_list()
        for relics in in_relics_list:
            equip_updated = False
            if relics.suit is Artifacts.SUIT_A:
                equip_updated = update_cur_equip(equip_map, relics)
            if not equip_updated:
                salvage_count += 1
        if salvage_count >= 10:
            salvage_count -= 10
            synthetic_relics = get_need_out_relics_type(equip_map, [Sphere, Link])(Artifacts.SUIT_A)
            equip_updated = update_cur_equip(equip_map, synthetic_relics)
            if not equip_updated:
                salvage_count += 1

    if display:
        for item in equip_map.values():
            print(item['relics'])
            print('score: %.1f\n' % item['score'])
    return times
